from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from apps.meiduo_admin.serializers.orders import OrderInfoSerializer
from apps.meiduo_admin.utils import PageNum
from apps.orders.models import OrderInfo






#############获取订单
class OrderView(ReadOnlyModelViewSet):
    #指定序列化器
    serializer_class = OrderInfoSerializer
    #指定查询集
    queryset = OrderInfo.objects.all()
    #指定分页器
    pagination_class = PageNum

    # 重写get_queryset
    def get_queryset(self):
        # 根据keyword参数返回不同查询结果
        keyword = self.request.query_params.get("keyword")

        if keyword == "" or keyword is None:
            #返回数据
            return OrderInfo.objects.all()
        else:
            # 返回查询数据
            return OrderInfo.objects.filter(order_id__contains=keyword)


    ######修改订单状态######
    #自动生成路由
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        # 1.根据id查询订单对象
        try:
            order=OrderInfo.objects.get(order_id=pk)
        except:
            return Response({"error":"订单信息错误"},status=400)
        # 2.获取订单状态编号
        status = request.data.get("status")
        # 3.修改订单状态
        order.status = status
        order.save()
        # 4.返回订单信息
        return Response({"status":status})